
package com.tocea.formation.users;


import java.util.Iterator;
import java.util.List;

public final class UserManager
{
    
    private List<IUser> users;
    
    public UserManager(List<IUser> users) {
    
        super();
        this.users = users;
    }
    
    public IUser connectUser(String _id, String _password) throws NotSuchUserException {
    
        IUser res = null;
        boolean find = false;
        for (Iterator<IUser> iterator = users.iterator(); !find && iterator.hasNext();) {
            IUser user = iterator.next();
            if (user.getId().equals(_id) && user.getpassword().equals(_password)) {
                res = user;
                find = true;
            }
            
        }
        if (!find) throw new NotSuchUserException("User with id = " + _id + " and password = " + _password + " does not exist");
        
        return res;
    }
    
    public boolean existUser(String _id, String _password) {
    
        boolean find = false;
        for (Iterator<IUser> iterator = users.iterator(); !find && iterator.hasNext();) {
            IUser user = iterator.next();
            if (user.getId().equals(_id) && user.getpassword().equals(_password)) {
                find = true;
            }
            
        }
        
        return find;
    }
    
    public IUser createUser(String _name, String _id, String _password) {
    
        IUser res = null;
        if (existUser(_id, _password)) {
           throw new IllegalArgumentException("Impoosible de créer le nouvel utilisateur, un abboné avec ce login et ce password exist deja");
        } else {
            res = UserFactory.INSTANCE.createUser(_name, _id, _password);
            users.add(res);
        }
        return res;
        
    }
    public IUser deleteUser(String _id, String _password) throws NotSuchUserException {
    
        IUser res = null;
        if (existUser(_id, _password)) {
            users.remove(connectUser(_id, _password));
        } else
            throw new NotSuchUserException(
                    ("User with id = " + _id + " and password = " + _password + " does not exist, si Ot can't be deleted"));
        return res;
        
    }
}
